<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import {
  deleteDepartmentDataApi,
  updateDepartmentDataApi,
  getDepartmentDataApi,
  addDepartmentDataApi
} from "@/api/department"

import {
  type IGetDepartmentData,
  IAddDepartmentRequestData,
  IUpdateDepartmentRequestData
} from "@/api/department/types/department"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox, ElTable } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { hasAnthority } from "@/utils"
defineOptions({
  name: "ElementPlus"
})

const loading = ref(false)
const singleTableRef = ref<InstanceType<typeof ElTable>>()
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const addDialogVisible = ref<boolean>(false)
const addFormRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  note: ""
})

const addFormData = reactive<IAddDepartmentRequestData>({
  name: "",
  note: "",
  coding: ""
})

const addFormRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入名称" }]
})

const resetForm = (formEl: FormInstance | null) => {
  if (!formEl) return
  formEl.resetFields()
  currentUpdateId.value = undefined
}
//#endregion

//#region 删
const handleDelete = (row: IGetDepartmentData) => {
  ElMessageBox.confirm(`正在删除办学单位：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteDepartmentDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getDepartmentData()
    })
  })
}
//#endregion
const handleConfirmAdd = () => {
  if (currentUpdateId.value) {
    updateFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        updateDepartmentDataApi(updateData.value).then(() => {
          ElMessage.success("修改成功")
          updateDialogVisible.value = false
          getDepartmentData()
        })
      } else {
        return false
      }
    })
  } else {
    addFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        addDepartmentDataApi(addFormData).then(() => {
          ElMessage.success("新增成功")
          addDialogVisible.value = false
          getDepartmentData()
        })
      } else {
        return false
      }
    })
  }
}
//#endregion

//#region 改
const updateFormRef = ref<FormInstance | null>(null)
const updateDialogVisible = ref<boolean>(false)
const updateType = ref("")
const currentUpdateId = ref<undefined | number>(undefined)
const updateData = ref<IUpdateDepartmentRequestData>({
  id: "",
  name: "",
  note: "",
  coding: ""
})
const handleUpdate = (row: IGetDepartmentData) => {
  currentUpdateId.value = row.id
  updateData.value = JSON.parse(JSON.stringify(row))
  formData.name = row.name
  updateDialogVisible.value = true
}
//#endregion

//#region 查
const DepartmentData = ref<IGetDepartmentData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: ""
})

const getDepartmentData = async () => {
  loading.value = true
  getDepartmentDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name || undefined
  })
    .then((res) => {
      paginationData.total = res.data.total
      DepartmentData.value = res.data.list
    })
    .catch(() => {
      DepartmentData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getDepartmentData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getDepartmentData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getDepartmentData()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getDepartmentData, {
  immediate: true
})
</script>

<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="办学单位名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="mb-5" shadow="never">
      <div class="toolbar-wrapper">
        <div v-if="hasAnthority('department.add')">
          <el-button type="primary" :icon="CirclePlus" @click="addDialogVisible = true">新增办学单位</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper college">
        <el-table ref="singleTableRef" :data="DepartmentData" highlight-current-row style="width: 100%">
          <el-table-column prop="name" label="单位名称" align="center" />
          <el-table-column prop="coding" label="单位编号" align="center" />
          <el-table-column prop="note" label="备注" align="center" />
          <el-table-column fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button
                v-if="hasAnthority('department.update')"
                type="primary"
                text
                bg
                size="small"
                @click="
                  () => {
                    handleUpdate(scope.row)
                    updateType = 'college'
                  }
                "
                >修改</el-button
              >
              <el-button
                v-if="hasAnthority('department.delete')"
                type="danger"
                text
                bg
                size="small"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pager-wrapper">
        <el-pagination
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 修改 -->
    <el-dialog
      v-model="updateDialogVisible"
      title="修改办学单位"
      @close="resetForm(addFormRef)"
      width="40%"
      label-position="left"
    >
      <el-form
        ref="updateFormRef"
        :model="updateData"
        :rules="addFormRules"
        label-width="110px"
        label-position="right"
        class="mt-5"
      >
        <el-form-item prop="name" label="单位名称">
          <el-input v-model="updateData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="coding" label="单位编号">
          <el-input v-model="updateData.coding" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="note" label="备注">
          <el-input v-model="updateData.note" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAdd">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="addDialogVisible"
      title="新增办学单位"
      @close="resetForm(addFormRef)"
      width="40%"
      label-position="left"
    >
      <el-form
        ref="addFormRef"
        :model="addFormData"
        :rules="addFormRules"
        label-width="110px"
        label-position="right"
        class="mt-5"
      >
        <el-form-item prop="name" label="办学单位名称">
          <el-input v-model="addFormData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="coding" label="办学单位编号">
          <el-input v-model="addFormData.coding" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="note" label="备注">
          <el-input v-model="addFormData.note" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAdd">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.college :deep(.el-table) {
  --el-table-current-row-bg-color: #fdf6ec;
  // --el-table-row-hover-bg-color: #001428;
}
</style>
